<template>
  <a-modal
    :title="isEdit ? '编辑' : '新增'"
    :visible="visible"
    :confirm-loading="confirmLoading"
    :width="800"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-spin :spinning="isEdit && editLoading">
      <a-form-model
        ref="ruleForm"
        :model="formData"
        :rules="rules"
        labelAlign="left"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-row :gutter="20">
          <a-col :span="7">
            <a-form-model-item label="编号">
              <a-input v-model="formData.shift_no" :disabled="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="10">
            <a-form-model-item label="名称" prop="shift_name">
              <a-input v-model="formData.shift_name" placeholder="请输入" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="周期" prop="shift_cyc">
              <a-input-number v-model="formData.shift_cyc" :min="0" :max="999999999999" style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-form-model-item label="部门" :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }">
            <a-tree-select
            v-model="formData.dep_id"
            :dropdown-style="{ maxHeight: '400px',  overflow: 'auto' }"
            placeholder="请选择部门"
            allow-clear
            :tree-default-expand-all="false"
            :treeData="departmentList"
            :replaceFields="{children:'childs', title:'dep_name', key:'pkey', value: 'pkey' }"
          >
          </a-tree-select>
          </a-form-model-item>
        <a-row :gutter="20">
          <a-col :span="18">
            <a-form-model-item label="备注" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
              <a-textarea v-model="formData.remark" :auto-size="{ minRows: 1, maxRows: 5 }" placeholder="请输入" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="是否默认" :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }">
              <a-checkbox v-model="formData.def_shift"></a-checkbox>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-form-model-item label="明细" :label-col="{ span: 2 }" :wrapper-col="{ span: 22 }">
          <a-table
            size="middle"
            rowKey="order_no"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :columns="columns"
            :scroll="{ y: 280 }"
            :data-source="dataSource"
            bordered
            :loading="loading"
          >
            <template slot="index" slot-scope="text, record, index">
              {{ index + 1 }}
            </template>
            <template slot="action" slot-scope="text, record, index">
              <a-button type="link" @click="handleEdit(record, index)" size="small">编辑</a-button>
            </template>
          </a-table>
        </a-form-model-item>
        <a-row>
          <a-col :span="2"></a-col>
          <a-col :span="18">
            <a-button @click="handleAdd" type="primary" icon="plus" class="l-mg-r10">新增</a-button>
            <a-button @click="handleDel" type="danger" icon="delete" :disabled="!hasSelected">删除</a-button>
          </a-col>
        </a-row>
        <a-modal
          :title="tableEdit ? '编辑' : '新增'"
          :visible="tableVisible"
          :confirm-loading="confirmTableLoading"
          @ok="handleTableOk"
          @cancel="tableVisible = false"
        >
          <a-form-model :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
            <a-form-model-item label="序号">
              <a-input :value="edit_order_no" :disabled="true" />
            </a-form-model-item>
            <a-form-model-item label="班次">
              <a-select v-model="class_key" style="width: 100%">
                <a-select-option v-for="item in classTypeList" :key="item.pkey" :value="item.pkey">{{
                  item.class_name
                }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-form-model>
        </a-modal>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
import { editShiftAttClassApi, getShiftAttClassDetailApi, getAttClassSelectListApi } from '@/api/attendance'
import { getDepartmentList } from '@/api/plan'
export default {
  computed: {
    hasSelected() {
      return this.selectedRowKeys.length > 0
    },
  },
  data() {
    const columns = [
      {
        title: '序号',
        align: 'center',
        dataIndex: 'order_no',
        width: 100,
      },
      {
        title: '名称',
        dataIndex: 'class_name',
      },
      {
        title: '操作',
        width: 120,
        align: 'center',
        scopedSlots: { customRender: 'action' },
      },
    ]
    return {
      isEdit: false,
      visible: false,
      confirmLoading: false,
      pkey: null,
      formData: {
        shift_no: null, // 编号
        shift_name: '', // 名称
        dep_id: null, // 部门
        shift_cyc: null, // 周期
        remark: '', // 备注
        def_shift: false, // 是否默认
      },
      rules: {
        shift_name: [{ required: true, message: '请输入名称', trigger: 'change' }],
        shift_cyc: [{ required: true, message: '请输入周期', trigger: 'change' }],
      },
      loading: false,
      columns: columns,
      dataSource: [],
      selectedRowKeys: [],
      selectedRows: [],
      tableEdit: false,
      tableVisible: false,
      class_key: '',
      edit_order_no: '',
      confirmTableLoading: false,
      currentTableIndex: -1,
      classTypeList: [],
      departmentList: [], // 部门列表
      editLoading: false
    }
  },
  created() {
    this.getAttClassSelectList()
    this.getDepartmentList()
  },
  methods: {
    add(shift_no) {
      this.isEdit = false
      this.visible = true
      this.pkey = null
      this.resetForm()
      this.formData.shift_no = shift_no
    },
    edit(row) {
      this.isEdit = true
      this.visible = true
      this.pkey = row.pkey
      this.resetForm()
      this.getShiftAttClassDetail()
    },
    resetForm() {
      if(this.departmentList.length > 0) {
        this.formData.dep_id = this.departmentList[0].pkey
      }
      this.formData.shift_no = null
      this.formData.shift_name = ''
      this.formData.shift_cyc = null
      this.formData.remark = ''
      this.formData.def_shift = false
      this.dataSource = []
      this.selectedRowKeys = []
      this.selectedRows = []
    },
    handleOk() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.confirmLoading = true
          // 处理数据
          let formObj = { ...this.formData }
          formObj.def_shift = formObj.def_shift === true ? 1 : 0
          let list = JSON.parse(JSON.stringify(this.dataSource))
          for (let i = 0; i < list.length; i++) {
            delete list[i].class_name
          }
          formObj.classes = list
          if (this.isEdit) {
            formObj.pkey = this.pkey
          } else {
            delete formObj.pkey
          }
          const { statusCode, errors } = await editShiftAttClassApi(formObj)
          this.confirmLoading = false
          if (statusCode == 200) {
            this.visible = false
            this.$message.success('保存成功！')
            this.$emit('saveSuccess')
            this.resetForm()
            this.$parent.getTableData()
          } else {
            this.$message.error(errors)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
    handleAdd() {
      this.tableEdit = false
      this.class_key = ''
      this.tableVisible = true
      this.edit_order_no = this.dataSource.length > 0 ? this.dataSource[this.dataSource.length - 1].order_no + 1 : 1
    },
    handleTableOk() {
      this.confirmTableLoading = true
      let classNameList = this.classTypeList.filter((item) => item.pkey === this.class_key)
      let class_name = ''
      if (classNameList.length > 0) {
        class_name = classNameList[0].class_name
      }
      if (this.tableEdit) {
        this.dataSource[this.currentTableIndex].class_key = this.class_key
        this.dataSource[this.currentTableIndex].class_name = class_name
      } else {
        this.dataSource.push({
          order_no: this.dataSource.length + 1,
          class_key: this.class_key,
          class_name,
        })
      }
      this.confirmTableLoading = false
      this.tableVisible = false
    },
    handleDel() {
      for (let i = 0; i < this.selectedRowKeys.length; i++) {
        this.dataSource.splice(this.selectedRowKeys[i].index, 1)
      }
      this.selectedRowKeys = []
      this.selectedRows = []
    },
    handleEdit(row, index) {
      this.edit_order_no = row.order_no
      this.tableEdit = true
      this.currentTableIndex = index
      this.class_key = row.class_key
      this.tableVisible = true
    },
    // 选择数据
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    // 轮班详情
    async getShiftAttClassDetail() {
      this.editLoading = true
      const { data } = await getShiftAttClassDetailApi({
        pkey: this.pkey,
      })
      this.editLoading = false
      this.formData.shift_no = Number(data.shift_no)
      this.formData.shift_name = data.shift_name
      this.formData.shift_cyc = data.shift_cyc
      this.formData.remark = data.remark
      this.formData.def_shift = data.def_shift == 1 ? true : false
      this.formData.dep_id = data.dep_id
      this.dataSource = data.classes
    },
    // 获取班次列表
    async getAttClassSelectList() {
      const { data } = await getAttClassSelectListApi()
      this.classTypeList = data
    },
    // 获取部门列表
    async getDepartmentList () {
      const { data } = await getDepartmentList()
      this.departmentList = data
      if(data && !this.isEdit) {
        this.formData.dep_id = data[0].pkey
      }
    },
  },
}
</script>

<style lang="less" scoped>
</style>